package top.winshu.common.web.context;


import org.aspectj.lang.JoinPoint;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class RequestContextUtil {

    /**
     * 记录每次请求信息
     */
    private static final ThreadLocal<RequestContext> REQUEST_BODY_THREAD_LOCAL = new ThreadLocal<>();

    public static void clear() {
        REQUEST_BODY_THREAD_LOCAL.remove();
    }

    public static void setRequestContext(HttpServletRequest request, JoinPoint joinPoint) {
        String controller = joinPoint.getSignature().getDeclaringTypeName();
        String method = joinPoint.getSignature().getName();

        RequestContext requestContext = new RequestContext();
        requestContext.setController(controller);
        requestContext.setMethod(method);
        requestContext.setArgs(joinPoint.getArgs());
        requestContext.setUrl(request.getRequestURI());
        requestContext.setAddress(request.getRemoteAddr());

        Enumeration<String> iter = request.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        while (iter.hasMoreElements()) {
            String key = iter.nextElement();
            headers.put(key, request.getHeader(key));
        }
        requestContext.setHeaders(headers);

        REQUEST_BODY_THREAD_LOCAL.set(requestContext);
    }

    public static RequestContext getRequestContext() {
        return REQUEST_BODY_THREAD_LOCAL.get();
    }

    public static String getHeader(String key) {
        RequestContext requestContext = getRequestContext();
        if (requestContext == null || key == null) {
            return null;
        }
        return getRequestContext().getHeaders().get(key.toLowerCase());
    }
}
